﻿package net.wangit.dev.unit;

import java.util.List;

import net.wangit.LabelUtil;
import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.jdbc.table.Column;
import net.wangit.jdbc.table.TableMeta;
import net.wangit.jdbc.table.TableMetaFactory;
import net.wangit.view.page.PageCache;
import net.wangit.view.unit.UnitCache;


public class JoinElementsAction extends DomainAction {

	private static final String SQL = "select * from ELEMENT where uid=? ";

	public JoinElementsAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String sourceUnitId = ac.getRequestParameter("unit.import.source");
		String targetUnitId = JoinElementsUI.getTargetUnitId();
		String checks[] = ac.getRequestParameters("_s_elements");
		String ids_soruce[] = ac.getRequestParameters("elements.eid");
		String ids_target[] = ac.getRequestParameters("elements.id");
		MapList elements = db.query(JoinElementsAction.SQL, sourceUnitId, 2);
		TableMeta meta = TableMetaFactory.getTableMeta("dev", "ELEMENT");
		List<Column> columns = meta.getColumns();
		Table table = new Table("dev", "ELEMENT");
		int count = 0;
		for (int i = 0; i < checks.length; i++)
			if ("1".equals(checks[i])) {
				int rowIndex = elements.findRowIndex("eid", ids_soruce[i]);
				if (rowIndex >= 0) {
					Row row = elements.getRow(rowIndex);
					addElement(table, columns, row, targetUnitId, ids_target[i]);
					count++;
				}
			}

		db.save(table);
		ac.getActionResult().addInfo(
				LabelUtil.get(ac, "dev", "import.1", Integer.toString(count)));
		UnitCache.clear(domain, targetUnitId);
		PageCache.clear(domain, targetUnitId);
	}

	private final void addElement(Table table, List<Column> columns, Row row,
			String unitId, String elementId) {
		ColumnRow cRow = table.addInsertRow();
		for (int i = 0; i < columns.size(); i++) {
			Column column = columns.get(i);
			String columnName = column.getName();
			cRow.set(columnName, row.get(columnName));
		}

		cRow.set("uid", unitId);
		cRow.set("eid", elementId);
	}
}
